import java.util.Arrays;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;

/**
*The <code>InventoryFile</code> class stores the Inventory objects in and array.
*It uses a simple text file to load data and to save data.
*@author Thomas Pierson (Team 2)
*@version 1.0
**/
public class InventoryFile
{
    private static final String fileName = "inventory.txt"; // file containing data
    private static final int maxProd = 100;  // maximum number of products
    private int numProd = 0;                 // current number of products
    private Inventory invArray[] = new Inventory[maxProd];

/**
*Creates an <code>InventoryFile</code> object
**/
    public InventoryFile()
    {
        loadData();
    }

/**
*Reads in the data records from a text file. The record format is:
*ProductID,Manufacturer,Size,Price,Quantity\n
*There are no spaces after commas
**/
    private void loadData()
    {
        String line = "";
        numProd = 0;

        try {
            Scanner inFile = new Scanner(new File(fileName));

            while (inFile.hasNextLine()) {
                line = inFile.nextLine();
                String[] s = line.split(",");
                invArray[numProd] = new
                    Inventory(Integer.parseInt(s[0]),s[1],s[2],Double.parseDouble(s[3]),Integer.parseInt(s[4]));
                ++numProd

;
            }
            inFile.close();
        } 
        catch (IOException e) {
            System.out.println("An IO error occurred while loading data.");
        }
    }

/**
*Saves the array of Inventory objects to a text file.
**/
    private void saveData()
    {
        try {
            PrintWriter out =   new PrintWriter(
                                new BufferedWriter(
                                new FileWriter(fileName)));

            for(int i=0; i < numProd; i++) {
                out.print(invArray[i].getItemNum() + ",");
                out.print(invArray[i].getManufacturer() + ",");
		    out.print(invArray[i].getSize() + ",");
                out.print(invArray[i].getPrice() + ",");
                out.println(invArray[i].getQuantity());
            }
            out.close();
        }
        catch (IOException e) {
            System.out.println("An IO error occurred while saving data.");
        }
    }

/**
*Creates a String containing all inventory records.
*@return  A <code>String</code> object containing all the records in the
*current order.
**/
    public String toString()
    {
        String s = "";

        for (int i=0; i < numProd; i++) {
            s += invArray[i].getItemNum() + ": ";
            s += invArray[i].getManufacturer() + ", ";
            s += invArray[i].getSize() + ", ";
	      s += invArray[i].getPrice() + ", ";
            s += invArray[i].getQuantity() + "\n";
        }
        return s;
    }

/**
*Adds a new inventory item to the array.
*@param itemNum An <code>int</code> specifying an inventory ID number.
*@param manufacturer A <code>String</code> specifying a manufacturer.
*@param size A <code>String</code> specifying a flash drive size.
*@param price A <code>double</code> specifying a price.
*@param quantity A <code>int</code> specifying the quantity.
**/   
    public void addItem(int itemNum, String manufacturer, String size, double price, int quantity)
    {
	  invArray[numProd] = new Inventory(itemNum, manufacturer, size, price, quantity);
	  numProd++;
	  saveData();
    }

/**
*Deletes an inventory item from the array. 
*@param eNum An <code>int</code> specifying the unique employee ID number.
*@return foundMatch A <code>boolean</code> specifying if employee is 
* deleted. True = deleted and false means the employee was not found.
**/
    public boolean deleteItem(int invNum)
    {
        int index = 0;
        boolean foundMatch = false;
        while (foundMatch == false && index < numProd) {
            if (invArray[index].getItemNum() == invNum) {
                foundMatch = true;
                --numProd;

                // Remove this element by copying the next element over this one.
                // Repeat the process until we reach the end of the array.
                while (index < numProd) {
                    invArray[index] = invArray[index+1];
                    ++index;
                }

                // We now have 2 copies of the last element. So set the very last
                // one to null. 
                invArray[numProd] = null;
                saveData();
            }
            ++index;
        }
        return foundMatch;
    }

/**
*Searches for an inventory record by the itemNum and returns data as String
*@param itemNum An <code>int</code> specifying the unique inventory ID number.
*@return results A <code>String</code> containing all inventory records
*that match this itemNum.
**/
    public String searchItemNum(int itemNum)
    {
        String results = "";
        for (int i=0; i<numProd; i++) {
            if (invArray[i].getItemNum() == itemNum) {
                results += invArray[i].toString() + "\n";
            }
        }
        return results;
    }           


    public static void main(String args[])
    {
	InventoryFile fileDB = new InventoryFile();
	System.out.println(fileDB.toString());
    }
}


